package com.speech.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.speech.MyApplication;
import com.speech.R;
import com.speech.constant.PrefsConstant;
import com.speech.db.SharedPreferenceHelper;
import com.speech.entity.BaseEntity;
import com.speech.http.BaseCallback;
import com.speech.net.BasicCallBack;
//import com.speech.net.HttpCommunicationManager;
import com.speech.net.constant.EnumRegisterType;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.net.request.UserRegister_Request;
import com.speech.net.result.UpdateInfo_Result;
import com.speech.net.result.UserAuth_Result;
import com.speech.result.Result;
import com.speech.utils.ApkVersionUtil;
import com.speech.utils.DeviceUtil;
import com.speech.utils.JsonProcessor;

import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;

import retrofit2.Call;

public class RegisterActivity extends BaseActivity {

    private EditText edt_account;
    private EditText edt_verification;
    private EditText edt_password;

    private TextView tv_request;
    private TextView tv_login;

    private Button btn_submit;

    private final int TAG_TIME_COUNTING = 100;
    private final int TAG_TIME_DONE = 101;

    private Handler mHandler;

//    private HttpCommunicationManager httpc;

    private boolean bGetCaptcha = true;
    private SweetAlertDialog dialog;
    private SweetAlertDialog dialog1;
    private SweetAlertDialog dialog2;
    private SweetAlertDialog dialog3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        _initView();

        //TODO:临时的升级检查
        _temp_check_version_change();

//        httpc = HttpCommunicationManager.getInstance();

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == TAG_TIME_COUNTING) {
                    tv_request.setText(msg.arg1 + "s后重发");
                } else if (msg.what == TAG_TIME_DONE) {
                    tv_request.setText("获取验证码");
                    _check_request_able();
                }
            }
        };

        edt_account.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                _check_request_able();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        // 验证码输入监听
        edt_verification.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (edt_verification.getText() != null && edt_verification.getText().toString().length() > 0) {
                    btn_submit.setClickable(true);
                    btn_submit.setTextColor(Color.WHITE);
                } else {
                    btn_submit.setClickable(false);
                    btn_submit.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        // 发送短信验证码请求
        tv_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


//                MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(RegisterActivity.this, EnumReqestActionCode.申请验证码, "{\"phone\":" + edt_account.getText().toString() + "}");
//                String json = JsonProcessor.StcGetJson(msg_c2s);
//
//                httpc.doPost(json, _generate_register_call_back(json));


                if (TextUtils.isEmpty(edt_account.getText().toString())){
                    Toast.makeText(RegisterActivity.this,"请输入手机号！",Toast.LENGTH_LONG).show();
                }
                Log.e("Phone",edt_account.getText().toString());


                sendCode();


                tv_request.setClickable(false);
                tv_request.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));

                tv_request.setText("60s后重发");

                // 控制倒计时显示
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int iCountDown = 60;
                        while (iCountDown > 0) {
                            Message msg = new Message();
                            msg.arg1 = iCountDown;
                            msg.what = TAG_TIME_COUNTING;
                            mHandler.sendMessage(msg);
                            iCountDown--;
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        mHandler.sendEmptyMessage(TAG_TIME_DONE);
                    }
                }).start();
            }
        });

        //提交注册
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.PROGRESS_TYPE);
                dialog.setTitleText("Loading");
                dialog.setCancelable(false);
                dialog.show();
                if (!bGetCaptcha) {
                    //还没有获取验证码

                    return;
                }

                UserRegister_Request register_request = new UserRegister_Request();
                register_request.phone = Long.valueOf(edt_account.getText().toString());
                register_request.registerType = EnumRegisterType.手机号;
                register_request.strVerifyCode = edt_verification.getText().toString();
                register_request.strNickName = edt_account.getText().toString();
                register_request.strPassword = edt_password.getText().toString();
                SharedPreferenceHelper spf = new SharedPreferenceHelper(RegisterActivity.this, PrefsConstant.FILE_USER_INFO);
                Long lUID = (Long) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, SharedPreferenceHelper.LONG_TYPE_DEFAULT);
                if (lUID != SharedPreferenceHelper.LONG_TYPE_DEFAULT) {
                    register_request.uid = lUID;
                }


                // TODO:注册借口
//                MessageC2S messageC2S = MessageC2SBuilder.buildGeneral_MessageC2S(RegisterActivity.this, EnumReqestActionCode.注册, JsonProcessor.StcGetJson(register_request));
//                final String json = JsonProcessor.StcGetJson(messageC2S);
//
//                httpc.doPost(json, new BasicCallBack(RegisterActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//                    @Override
//                    public void success(MessageS2C msg_s2c) {
//                        dialog.dismiss();
//                        UserAuth_Result rst = JsonProcessor.StcGetObject(UserAuth_Result.class, msg_s2c.strData);
//                        SharedPreferenceHelper spf = new SharedPreferenceHelper(RegisterActivity.this, PrefsConstant.FILE_USER_INFO);
//                        spf.putData(PrefsConstant.KEY_USER_INFO_INT_LOGIN_STATE,1);
//                        spf.putData(PrefsConstant.KEY_USER_INFO_LONG_UID, rst.uid);
//                        spf.putData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, rst.token);
//
//                        Log.d("fzw", "uid:" + rst.uid + "    token:" + rst.token);
//
//                        //注册成功直接跳到首页
//                        startActivity(new Intent(RegisterActivity.this, HomeActivity.class));
//                        finish();
//                    }
//
//                    @Override
//                    public void fail(MessageS2C msg_s2c) {
//                        dialog.dismiss();
//                        new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
//                                .setTitleText("错误")
//                                .setContentText(msg_s2c.strMsgUI)
//                                .setConfirmText("OK")
//                                .show();
//                    }
//                }));
                Call<Result<BaseEntity>> call = MyApplication.getInstance()
                        .getApiService().registe(edt_account.getText().toString(),edt_password.getText().toString()
                        ,"",edt_verification.getText().toString());
                call.enqueue(new BaseCallback<BaseEntity>() {
                    @Override
                    public void onSuccess(BaseEntity baseEntity) {
                        dialog.dismiss();
                        UserAuth_Result rst = JsonProcessor.StcGetObject(UserAuth_Result.class, baseEntity.getContent());
                        SharedPreferenceHelper spf = new SharedPreferenceHelper(RegisterActivity.this, PrefsConstant.FILE_USER_INFO);
                        spf.putData(PrefsConstant.KEY_USER_INFO_INT_LOGIN_STATE,1);
                        spf.putData(PrefsConstant.KEY_USER_INFO_LONG_UID, rst.uid);
                        spf.putData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, rst.token);

                        Log.d("fzw", "uid:" + rst.uid + "    token:" + rst.token);

                        //注册成功直接跳到首页
                        startActivity(new Intent(RegisterActivity.this, HomeActivity.class));
                        finish();
                    }

                    @Override
                    public void onAbnormal(String msg) {
                        dialog.dismiss();
                        Toast.makeText(RegisterActivity.this,msg,Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onFailure(String msg) {
                        dialog.dismiss();
                        dialog1 = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("错误")
                                .setContentText(msg)
                                .setConfirmText("OK");
                                dialog1.show();
                    }
                });
            }
        });

        //前往登陆
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });

    }

    private void sendCode(){
        Call<Result<BaseEntity>> call = MyApplication.getInstance()
                        .getApiService().sendCode(edt_account.getText().toString());
        call.enqueue(new BaseCallback<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity baseEntity) {
                bGetCaptcha = true;
                Toast.makeText(RegisterActivity.this,"发送成功！",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onAbnormal(String msg) {
                Toast.makeText(RegisterActivity.this,msg,Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(String msg) {
                Toast.makeText(RegisterActivity.this,msg,Toast.LENGTH_LONG).show();
            }
        });
    }


    private BasicCallBack _generate_register_call_back(final String json) {
        return new BasicCallBack(RegisterActivity.this, json, new BasicCallBack.BasicCallBackListener() {
            @Override
            public void success(MessageS2C msg_s2c) {
                //请求成功
                bGetCaptcha = true;
                Toast.makeText(RegisterActivity.this,msg_s2c.strMsgUI,Toast.LENGTH_LONG).show();
            }

            @Override
            public void fail(MessageS2C msg_s2c) {
                dialog2 = new SweetAlertDialog(RegisterActivity.this,SweetAlertDialog.ERROR_TYPE)
                        .setTitleText(msg_s2c.strMsgUI)
                        .setConfirmText("OK");
                        dialog2.show();
            }
        });
    }

    private void _check_request_able() {
        if (edt_account.getText() != null && edt_account.getText().toString().length() == 11) {
            tv_request.setClickable(true);
            tv_request.setTextColor(getResources().getColor(R.color.colorOrange));
        } else {
            tv_request.setClickable(false);
            tv_request.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));
        }
    }

    private void _initView() {
        edt_account = findViewById(R.id.edt_register_account);
        edt_verification = findViewById(R.id.edt_register_verification);
        edt_password = findViewById(R.id.edt_register_password);

        tv_request = findViewById(R.id.tv_register_request);
        tv_request.setClickable(false);

        tv_login = findViewById(R.id.tv_register_login);

        btn_submit = findViewById(R.id.btn_register_submit);
        btn_submit.setClickable(false);
    }

    private void _temp_check_version_change() {

        //TODO: 接口请求
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(this, EnumReqestActionCode.查询更新, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(RegisterActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//                UpdateInfo_Result updateInfo_result = JsonProcessor.StcGetObject(UpdateInfo_Result.class, msg_s2c.strData);
//
//                if (updateInfo_result != null && _check_need_update(updateInfo_result)) {
//                    SweetAlertDialog dialog = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.WARNING_TYPE)
//                            .setTitleText("新版本上线啦")
//                            .setContentText("请进入公众号内下载最新版本")
//                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                                @Override
//                                public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                    sweetAlertDialog.dismiss();
//                                    MyApplication.getInstance().destory();
//                                    RegisterActivity.this.finish();
//                                }
//                            });
//                    dialog.setCancelable(false);
//                    dialog.show();
//                }
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//
//            }
//        }));

        String uid,token;
        SharedPreferenceHelper spf = new SharedPreferenceHelper(this, PrefsConstant.FILE_USER_INFO);
        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
        uid = lUID;
        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
        token = lToken;
        Call<Result<BaseEntity>> call = MyApplication.getInstance().getApiService()
                .upApp(uid, DeviceUtil.getDeviceID(this)
                        ,token,ApkVersionUtil.getVersionName(this));
        call.enqueue(new BaseCallback<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity baseEntity) {
//                dialog3 = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("新版本上线啦")
//                        .setContentText("请进入公众号内下载最新版本")
//                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                sweetAlertDialog.dismiss();
//                                MyApplication.getInstance().destory();
//                                RegisterActivity.this.finish();
//                            }
//                        });
//                dialog3.setCancelable(false);
//                dialog3.show();
            }

            @Override
            public void onAbnormal(String msg) {

            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    private boolean _check_need_update(UpdateInfo_Result updateInfo_result) {

        String[] strServerVersion = updateInfo_result.strEnforcementUpdateVersion.split("\\.");
        String[] strCurrentVersion = ApkVersionUtil.getVersionName(RegisterActivity.this).split("\\.");
        boolean bNeedUpdate = false;

        for (int index = 0; index < strServerVersion.length; index++) {
            int iServerVerison = Integer.valueOf(strServerVersion[index]);
            int iCurrentVersion = Integer.valueOf(strCurrentVersion[index]);
            if (iServerVerison > iCurrentVersion) {
                bNeedUpdate = true;
                break;
            }
        }

        return bNeedUpdate;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null){
            dialog.dismissWithAnimation();
        }
        if (dialog1 != null){
            dialog1.dismissWithAnimation();
        }
        if (dialog2 != null){
            dialog2.dismissWithAnimation();
        }
        if (dialog3 != null){
            dialog3.dismissWithAnimation();
        }
    }
}
